package com.clp.protocol.iec104.apdu.apci;

import com.clp.protocol.iec104.definition.ApduType;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.Objects;

@Getter
@NoArgsConstructor
@AllArgsConstructor
public class SCtrlArea extends CtrlArea<SCtrlArea> {
    /**
     * 接收序号
     */
    private int recvSeq;

    @Override
    public SCtrlArea initBy(ByteBuf buf) {
        buf.readShortLE(); // 跳过发送序号
        this.recvSeq = (buf.readShortLE() & 0xFFFF) >> 1;
        return this;
    }

    @Override
    public boolean isValid() {
        return recvSeq >= 0;
    }

    @Override
    public void writeTo(ByteBuf buf) {
        buf.writeByte(ApduType.SType.getTypeDef());
        buf.writeByte(0);
        buf.writeShortLE(recvSeq << 1);
    }

    @Override
    public String toString() {
        return "接收序号：" + recvSeq;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        SCtrlArea that = (SCtrlArea) o;
        return recvSeq == that.recvSeq;
    }

    @Override
    public int hashCode() {
        return Objects.hash(recvSeq);
    }
}
